package com.stationpc.dock

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.provider.Settings
import android.text.TextUtils
import android.view.KeyEvent
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import com.stationpc.dock.service.DockOverlayService
import android.util.Log

class MainActivity : AppCompatActivity() {

    private lateinit var startDockButton: Button
    private lateinit var stopDockButton: Button
    private lateinit var settingsButton: Button
    private val OVERLAY_PERMISSION_REQUEST_CODE = 1001

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        startDockButton = findViewById(R.id.startDockButton)
        stopDockButton = findViewById(R.id.stopDockButton)
        settingsButton = findViewById(R.id.settingsButton)

        setupButtons()

        // Show the prompt to enable accessibility service if it's not enabled
        if (!isAccessibilityServiceEnabled()) {
            showEnableAccessibilityPrompt()
        }
    }

    private fun setupButtons() {
        startDockButton.setOnClickListener {
            if (Settings.canDrawOverlays(this)) {
                startDockService()
            } else {
                requestOverlayPermission()
            }
        }

        stopDockButton.setOnClickListener {
            stopDockService()
        }

        settingsButton.setOnClickListener {
            startActivity(Intent(this, SettingsActivity::class.java))
        }
    }

    private fun startDockService() {
        val intent = Intent(this, DockOverlayService::class.java)
        startForegroundService(intent)
        Toast.makeText(this, "Dock service started", Toast.LENGTH_SHORT).show()
    }

    private fun stopDockService() {
        val intent = Intent(this, DockOverlayService::class.java)
        stopService(intent)
        Toast.makeText(this, "Dock service stopped", Toast.LENGTH_SHORT).show()
    }

    private fun requestOverlayPermission() {
        if (!Settings.canDrawOverlays(this)) {
            val intent = Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:$packageName"))
            startActivityForResult(intent, OVERLAY_PERMISSION_REQUEST_CODE)
        } else {
            startDockService()
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == OVERLAY_PERMISSION_REQUEST_CODE) {
            if (Settings.canDrawOverlays(this)) {
                startDockService()
            } else {
                Toast.makeText(this, "Overlay permission is required to show the dock", Toast.LENGTH_LONG).show()
            }
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_PAGE_DOWN) {
            toggleDockVisibility()
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    private fun toggleDockVisibility() {
        val intent = Intent(this, DockOverlayService::class.java)
        intent.action = DockOverlayService.ACTION_TOGGLE_VISIBILITY
        startService(intent)
    }

    private fun isAccessibilityServiceEnabled(): Boolean {
        val expectedComponentName = ComponentName(this, DockAccessibilityService::class.java)
        val enabledServices = Settings.Secure.getString(
            contentResolver,
            Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES
        )
        if (!TextUtils.isEmpty(enabledServices)) {
            val colonSplitter = TextUtils.SimpleStringSplitter(':')
            colonSplitter.setString(enabledServices)
            while (colonSplitter.hasNext()) {
                val componentName = colonSplitter.next()
                if (ComponentName.unflattenFromString(componentName) == expectedComponentName) {
                    return true
                }
            }
        }
        return false
    }

private fun showEnableAccessibilityPrompt() {
    AlertDialog.Builder(this)
        .setTitle("Enable Accessibility Service")
        .setMessage("To use all features, please enable the Accessibility Service for this app.")
        .setPositiveButton("Yes") { _, _ ->
            // Open TvSettings app instead of Accessibility Service directly
            val intent = Intent(Intent.ACTION_MAIN).apply {
                setClassName("com.android.tv.settings", "com.android.tv.settings.MainSettings")
                addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            }
            try {
                startActivity(intent)
            } catch (e: Exception) {
                Log.e("MainActivity", "Unable to open TvSettings", e)
            }
        }
        .setNegativeButton("No") { dialog, _ ->
            dialog.dismiss()
        }
        .setCancelable(false)
        .show()
}
}
